package com.franklin.java.utils;

import com.franklin.plugins.common.collection.PrettyArrayList;
import com.franklin.plugins.common.utils.DataCheckUtils;
import com.intellij.psi.PsiElement;
import com.intellij.psi.xml.XmlElement;
import com.intellij.psi.xml.XmlTag;
import com.intellij.psi.xml.XmlText;
import org.jetbrains.annotations.NotNull;

import java.util.List;
import java.util.function.Predicate;

/**
 * @author Franklin
 * @since 2021/9/17 16:25
 */
public class XmlTagUtils {

    public static List<XmlElement> findXmlChild(@NotNull XmlTag xmlTag){
        List<XmlElement> xmlElementList = new PrettyArrayList<>();
        PsiElement[] children = xmlTag.getChildren();
        for (PsiElement psiElement : children) {
            if (psiElement instanceof XmlText || psiElement instanceof XmlTag){
                xmlElementList.add((XmlElement) psiElement);
            }
        }
        return xmlElementList;
    }

    /**
     * 按照指定属性找到对应的子标签<br>
     * @author Franklin
     * @since 2021/9/17 16:28
     * @param parentTag:父标签
     * @param childName:字标签名
     * @param attributeName:匹配属性名
     * @param attributeValue:目标属性值
     * @return com.intellij.psi.xml.XmlTag
     */
    public static XmlTag findChildTag(XmlTag parentTag, String childName, String attributeName, String attributeValue) {
        return findChildTag(parentTag,childName,childTag -> {
            String attributeValueFromTag = childTag.getAttributeValue(attributeName);
            return DataCheckUtils.isNotEmpty(attributeValueFromTag) && attributeValueFromTag.equals(attributeValue);
        });
    }

    /**
     * 查找子节点<br>
     * @author Franklin
     * @since 2021/9/17 16:41
     * @param parentTag:父节点
     * @param childName:子节点名
     * @param checkSubTagPredicate:子节点校验函数
     * @return com.intellij.psi.xml.XmlTag
     */
    public static XmlTag findChildTag(XmlTag parentTag, String childName, Predicate<XmlTag> checkSubTagPredicate){
        PsiElement[] children = parentTag.getChildren();
        for (PsiElement child : children) {
            if (child instanceof XmlTag){
                XmlTag childTag = (XmlTag) child;
                if (childTag.getName().equals(childName)){
                    if (checkSubTagPredicate.test(childTag)){
                        return childTag;
                    }
                }
            }
        }
        return null;
    }
}
